package com.iwhalecloud.uncc.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.regexp.RE;
import org.apache.regexp.RECompiler;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
    /**普通的英文半角空格Unicode编码*/
    private static final int SPACE_32 = 32;

    /**中文全角空格Unicode编码(一个中文宽度)*/
    private static final int SPACE_12288 = 12288;

    /**普通的英文半角空格但不换行Unicode编码(== &nbsp; == &#xA0; == no-break space)*/
    private static final int SPACE_160 = 160;

    /**半个中文宽度(== &ensp; == en空格)*/
    private static final int SPACE_8194 = 8194;

    /**一个中文宽度(== &emsp; == em空格)*/
    private static final int SPACE_8195 = 8195;

    /**四分之一中文宽度(四分之一em空格)*/
    private static final int SPACE_8197 = 8197;

    /**窄空格*/
    private static final int SPACE_8201 = 8201;



    /***
     * 针对1对N公共参数,取条数大的resultMap作为最大行数，其他size为1的map累加相同的值
     * @param totalResultMapList
     * @param maxRow
     */
    public static void expandPublicList( List<List<Map<String, String>>> totalResultMapList,int maxRow){
       int totalResultMapListSize=totalResultMapList.size();
       for(int i=0;i<totalResultMapListSize;i++){
           List<Map<String, String>> mapList=totalResultMapList.get(i);
           int mapListSize=mapList.size();
           int addRow=maxRow-mapListSize;
          if(addRow>0) {
              Map firstItem = mapList.get(0);
              for (int j = 0; j < addRow; j++) {
                  mapList.add(firstItem);
              }
          }
       }
    }

    public static List<String> convertObjListToStrList(List<Object> objList){
        List<String> counterList = new ArrayList<>();
        for(Object obj :objList){
            counterList.add(obj + "");
        }
        return counterList;
    }

    public static List<Map<String, String>> convertListToMapList(List<String> list, String counter){
        List<Map<String, String>> mapList = new ArrayList<>();
        Map<String, String> map;
        if(CollectionUtils.isNotEmpty(list)){
            mapList = new ArrayList<>();
            for(String val : list){
                map = new LinkedHashMap<>();
                map.put(counter, val);
                mapList.add(map);
            }
        }else{
            map = new LinkedHashMap<>();
            map.put(counter, null);
            mapList.add(map);
        }
        return mapList;
    }

    public static List<Map<String, String>> mergeListMap(List<List<Map<String, String>>> totalMapList){
        Map<String, String> counterMap;
        List<Map<String, String>> finalMapList = new ArrayList<>();
        for(int i=0;i<totalMapList.get(0).size();i++){
            counterMap = new HashMap<>();
            for(List<Map<String, String>> list : totalMapList){
                counterMap.putAll(list.get(i));
            }
            finalMapList.add(counterMap);
        }
        return finalMapList;
    }

    /**
     * 去除字符串前后的空格, 包括半角空格和全角空格(中文)等各种空格, java的string.trim()只能去英文半角空格
     * @param str
     */
    public static String trim(String str) {
        if (StringUtils.isEmpty(str)) {
            return str;
        }

        char[] val = str.toCharArray();
        int st = 0;
        int len=val.length;
        while ((st < len) && isSpace(val[st])) {
            st++;
        }
        while ((st < len) && isSpace(val[len - 1])) {
            len--;
        }
        return ((st > 0) || (len < val.length)) ? str.substring(st, len) : str;
    }

    public static boolean isSpace(char aChar) {
        return aChar == SPACE_32 || aChar == SPACE_12288 || aChar == SPACE_160 || aChar == SPACE_8194
                || aChar == SPACE_8195 || aChar == SPACE_8197 || aChar == SPACE_8201;
    }


    /**
     * 分割参数
     *
     * @param paraSrc String
     * @param sepa    String
     * @return Map sample : "a=b,c=d,..."
     */
    public static Map splitPara(String paraSrc, String sepa) {
        if (paraSrc == null || paraSrc.trim().length() == 0) {
            return null;
        }

        LinkedHashMap paraMap = new LinkedHashMap();
        if (sepa == null || "".equals(sepa)) { // 默认分割参数的分隔符为“,”
            sepa = ",";
        }

        /**
         *
         */
        String[] paras = paraSrc.split(sepa);
        for (int i = 0, j = 0; i < paras.length; i++) {
            String[] tmpResult = paras[i].split("=");
            if (tmpResult.length >= 2) { // 2 a=b
                paraMap.put(tmpResult[0].trim(), tmpResult[1]);
            } else if (tmpResult.length == 1) {
                if (paras[i].indexOf("=") >= 0) { // 1 a=
                    paraMap.put(tmpResult[0].trim(), "");
                } else { // 0 a
                    paraMap.put("TEXT." + j, paras[i]);
                    j++;
                }
            }
        }

        return paraMap;
    }

    /**
     * 判断字符串是否匹配指定的正则表达式
     *
     * @param src
     * @param regexp
     * @return boolean
     */
    public static boolean isMatch(String src, String regexp) {
        RE r = new RE();
        RECompiler compiler = new RECompiler();
        r.setMatchFlags(RE.MATCH_SINGLELINE);
        r.setProgram(compiler.compile(regexp));
        return (r.match(src));
    }

    /**
     * 替换符合正则表达式的所有子字符串为新字符串
     *
     * @param src     String
     * @param pattern String
     * @param to      String
     * @return String
     */
    public static String replaceAll(String src, String pattern, String to) {
        if (src == null) {
            return null;
        }
        if (pattern == null) {
            return src;
        }

        StringBuffer sb = new StringBuffer();
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(src);

        int i = 1;
        while (m.find()) {
            m.appendReplacement(sb, to);
            i++;
        }
        m.appendTail(sb);
        return sb.toString();
    }

    /***
     *  excape regex string or use  Pattern.quote(s)
     * @param s
     * @return
     */
    public static String quoteReplacement(String s) {
       return s.replace("\\", "\\\\")
                .replace("*", "\\*")
                .replace("+", "\\+").replace("|", "\\|")
                .replace("{", "\\{").replace("}", "\\}")
                .replace("(", "\\(").replace(")", "\\)")
                .replace("^", "\\^").replace("$", "\\$")
                .replace("[", "\\[").replace("]", "\\]")
                .replace("?", "\\?").replace(",", "\\,")
                .replace(".", "\\.").replace("&", "\\&");
    }

    /**
     * 将字符串转换成map
     * @param str
     * @return
     */
    public static  Map str2Map(String str){
        String[] split = str.split(";");
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        for(int i=0;i<split.length;i++){
            if(i!=0){
                String[] split1 = split[i].split("=");
                stringStringHashMap.put(split1[0],split1[1]);
            }
        }
        return stringStringHashMap;
    }

    /**
     * 将字符串转为list
     * @param str
     * @return
     */
    public static List<String> str2List(String str){
        List<String> resList = new ArrayList<>();
        String[] arr = str.trim().split("\t");
        for(String value : arr){
            resList.add(value);
        }
        return resList;
    }

    public static Object castStringToX(Class<?> clazz, String str) {
        Object value = null;
        if ("java.lang.Integer".equals(clazz.getName()) || "int".equals(clazz.getName())) {
            value = Integer.parseInt(str);
        } else if ("java.lang.Boolean".equals(clazz.getName()) || "boolean".equals(clazz.getName())) {
            value = Boolean.parseBoolean(str);
        } else if ("java.lang.Long".equals(clazz.getName()) || "long".equals(clazz.getName())) {
            value = Long.parseLong(str);
        } else {
            value = str;
        }
        return value;
    }
    
    public static  Map parseMap(String msgbody){
		String[] split = msgbody.split(";");
		HashMap<String, String> stringStringHashMap = new HashMap<>();
		for(int i=0;i<split.length;i++){
			if(i!=0){
				String[] split1 = split[i].split("=");
				stringStringHashMap.put(split1[0],split1[1]);
			}
		}
		return stringStringHashMap;
	}


    public static boolean isInteger(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    /**
     * 字符替换
     * @param template
     * @param params
     * @param regex
     * @return
     */
    public static String regexReplace(String template, Map<String, Object> params, String regex) {
        StringBuffer sb = new StringBuffer();
        Matcher m = Pattern.compile(regex).matcher(template);
        while (m.find()) {
            String param = m.group();
            Object value = params.get(param.substring(2, param.length() - 1));
            m.appendReplacement(sb, value == null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }

    /**
     * 获取指定标签中的内容
     *
     * @param xml   传入的xml字符串
     * @param label 指定的标签
     */
    public static List<String> getFieldListByRegex(String xml, String label) {
        //正则表达式
        String regex = "<" + label + ">(.*?)</" + label + ">";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(xml);
        //匹配的有多个
        List<String> fieldList = new ArrayList<>();
        while (m.find()) {
            if (StringUtils.isNotEmpty(m.group(1).trim())) {
                fieldList.add(m.group(1).trim());
            }
        }
        return fieldList;
    }
    public static void addRecords(List<Map> value, List<Map> valueList)  {
        for (Map et : value) {
            valueList.add(et);
        }
    }

    public static List<Map<String,String>> duplicateList (List<Map> inList,List<String>columnName){
        List tempList=new ArrayList();
        Map<String,Map<String,String>> m1=new HashMap();
        for(Map map : inList){
            Map<String,String> tempMap=new HashMap();
            StringBuffer key=new StringBuffer();
            for(String col:columnName){
                tempMap.put(col, MapUtils.getString(map, col));
                key.append(MapUtils.getString(map, col)).append("_");
            }
            key.deleteCharAt(key.length()-1);
            m1.put(key.toString(),tempMap);
        }
        for(Map.Entry<String, Map<String,String>> entry : m1.entrySet()){
            tempList.add(entry.getValue());
        }
        return tempList;
    }

    public static void getRecursionMap(JSONArray jsonArray, List<Map<String,String>> totalMap,
                                        String[] counterArr, String moName){
        int childSize=jsonArray.size();
        for(int i=0;i<childSize;i++){
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            JSONArray jsonArray1=jsonObject.getJSONArray("children");
            if(jsonArray1 != null && jsonArray1.size()>0){
                getRecursionMap( jsonArray1,totalMap,counterArr,moName);
            }
            Map<String,String> rowMap=new LinkedHashMap<>();
            //组建第一个值
            for(String counter:counterArr){
                rowMap.put(moName+counter, jsonObject.get(counter)==null?null:jsonObject.getString(counter) );
            }
            totalMap.add(rowMap);
        }
    }
}
